import AuthAPI from "@/api/auth";
import UserAPI from "@/api/user";
import {resetRouter} from "@/router";
import {store} from "@/store";

import {LoginData} from "@/api/auth/model";
import {UserInfo} from "@/api/user/model";
import {TOKEN_KEY, X_KEY_SM2} from "@/enums/CacheEnum";

export const useUserStore = defineStore("user", () => {
    const user = ref<UserInfo>({
        roles: [],
        menus: [],
        perms: [],
        user: {}
    });

    /**
     * 登录
     *
     * @param {LoginData}
     * @returns
     */
    function login(loginData: LoginData) {
        return new Promise<void>((resolve, reject) => {
            AuthAPI.login(loginData)
                .then((response) => {
                    const {token, key} = response.data;
                    sessionStorage.setItem(TOKEN_KEY, token);
                    sessionStorage.setItem(X_KEY_SM2, key);
                    resolve();
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    // 获取信息(用户昵称、头像、角色集合、权限集合)
    function getUserInfo() {
        return new Promise<UserInfo>((resolve, reject) => {
            UserAPI.getInfo()
                .then((response) => {
                    let data = response.data
                    if (!data) {
                        reject("Verification failed, please Login again.");
                        return;
                    }
                    if (!data.roles || data.roles.length <= 0) {
                        reject("getUserInfo: roles must be a non-null array!");
                        return;
                    }
                    Object.assign(user.value, {...data});
                    user.value.userId = data.user.id
                    user.value.username = data.user.username
                    user.value.nickname = data.user.nickname
                    user.value.avatar = data.user.avatar
                    resolve(data);
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    // user logout
    function logout() {
        return new Promise<void>((resolve, reject) => {
            AuthAPI.logout()
                .then(() => {
                    user.value = {
                        roles: [],
                        menus: [],
                        perms: [],
                        user: {}
                    }
                    sessionStorage.setItem(TOKEN_KEY, "");
                    resetRouter();
                    location.reload(); // 清空路由
                    resolve();
                })
                .catch((error) => {
                    reject(error);
                });
        });
    }

    // remove token
    function resetToken() {
        return new Promise<void>((resolve) => {
            sessionStorage.setItem(TOKEN_KEY, "");
            resetRouter();
            resolve();
        });
    }

    return {
        user,
        login,
        getUserInfo,
        logout,
        resetToken,
    };
});

// 非setup
export function useUserStoreHook() {
    return useUserStore(store);
}
